package com.codedancer.campus.manager.schedule;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import com.codedancer.campus.common.dataresource.ExternalApiData;
import com.codedancer.campus.common.model.tx.HeadlineNewsModel;
import com.codedancer.campus.common.model.xr.BaiduHotModel;
import com.codedancer.campus.common.utils.UUIDGenerator;
import com.codedancer.campus.enums.HeadlineNewsType;
import com.codedancer.campus.mapper.HeadlineNewsMapper;
import com.codedancer.campus.po.HeadlineNews;
import java.util.Date;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * 百度热榜数据定时任务
 */
@Component
@Slf4j
public class BaiduHotDataSchedule {

    @Autowired
    private ExternalApiData externalApiData;

    @Autowired
    private HeadlineNewsMapper headlineNewsMapper;

    /**
     * 每隔1分钟拉去百度热搜
     */
    @Scheduled(cron = "0 0/1 * * * ?")
    public void pullBaiduHotData() {
        int putStorage = 0;
        List<BaiduHotModel> baiduHotModels = externalApiData.getBaiduHotData();
        if (CollUtil.isNotEmpty(baiduHotModels)) {
            for (BaiduHotModel baiduHotModel : baiduHotModels) {
                if (headlineNewsMapper.existsByColumn("title", baiduHotModel.getTitle())) {
                    continue;
                }
                HeadlineNews headlineNews = BeanUtil.copyProperties(baiduHotModel,
                    HeadlineNews.class);
                headlineNews.setUuid(UUIDGenerator.getUUID());
                headlineNews.setDescription(baiduHotModel.getDesc());
                headlineNews.setCoverImage(baiduHotModel.getPic());
                headlineNews.setUrl(baiduHotModel.getMobilUrl());
                headlineNews.setSource("百度");
                headlineNews.setPublishDate(new Date());
                headlineNews.setType(HeadlineNewsType.OTHER_NEWS);
                headlineNewsMapper.insert(headlineNews);
                putStorage++;
            }
            log.info("百度热搜拉取成功，入库成功，入库数量：{}", putStorage);
            return;
        }
        log.info("拉取的百度热搜数据为空");
    }
}
